#include <iostream>
#include "../comm/httplib.h"
#include "oj_control.hpp"
#include<signal.h>

using namespace httplib;
using namespace ns_control;


static Control* control_ptr;
void RecoveryMachine(int signo)
{
    control_ptr->RecoveryMachine();
}


int main()
{
    signal(SIGQUIT,RecoveryMachine);
    Server svr;
    Control control;
    control_ptr=&control;
    // 用户的三种请求
    // 1.获取题目列表页面

    svr.Get("/all_questions", [&control](const Request &req, Response &res)
            {
                // 返回一张包含所有题目的html网页
                std::string html;
                control.AllQuestions(&html);
                res.set_content(html, "text/html;charset=utf-8");
            });

    // 2.根据题目编号，获取题目内容页面
    svr.Get(R"(/question/(\d+))", [&control](const Request &req, Response &res)
            {
                std::string number = req.matches[1];
                // 返回题目编号对应的题目的html网页
                std::string html;
                control.Question(number, &html);
                res.set_content(html, "text/html;charset=utf-8");
            });
    // 3.用户提交代码，使用判题功能(1.每个题的测试 2.compile和run即compile_server服务)
    svr.Post(R"(/judge/(\d+))", [&control](const Request &req, Response &res)
             {
                 // res.set_content("提交代码","text/plain;charset=utf8");
                 std::string number = req.matches[1];
                 std::string out_json;
                 std::string in_json=req.body;
                 control.Judge(number,in_json,&out_json);
                 res.set_content(out_json,"application/json;charset=utf-8");
             });
    svr.set_base_dir("./wwwroot/");
    svr.listen("0.0.0.0", 8080);
}